package com.foot.travel.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import cn.beecloud.BeeCloud;

import com.foot.travel.R;
import com.foot.travel.event.NetRefreshEvent;
import com.foot.travel.viewholder.HotRecommendViewHolder;
import com.koalac.ironman.cache.SysAppConfig;
import com.koalac.ironman.common.adapter.CommonAdapter;
import com.koalac.ironman.common.module.ModuleActivity;
import com.koalac.ironman.net.MyRequest;
import com.koalac.ironman.net.ResponseCallback;
import com.koalac.ironman.net.pojo.request.CGetHomepage;
import com.koalac.ironman.net.pojo.request.Logout;
import com.koalac.ironman.net.pojo.response.HomeClass;
import com.koalac.ironman.net.pojo.response.HomePage;
import com.koalac.ironman.net.pojo.response.HotRecommend;
import com.koalac.ironman.net.pojo.response.Picture;
import com.koalac.ironman.net.pojo.response.Response;
import com.koalac.ironman.net.pojo.response.User;
import com.koalac.ironman.util.BeeCloudUtil;
import com.koalac.ironman.util.GBLActivityManager;
import com.koalac.ironman.util.ScreenInfoUtil;
import com.koalac.ironman.util.StringUtils;
import com.koalac.ironman.util.WeakHandler;
import com.koalac.ironman.viewhelper.ViewInject;
import com.koalac.ironman.widget.ImageLoadAgreement.ImageType;
import com.koalac.ironman.widget.LifeqImageView;
import com.koalac.ironman.widget.LoadingDialog;
import com.koalac.ironman.widget.ScrollViewPager;
import com.squareup.otto.Subscribe;
import com.umeng.update.UmengUpdateAgent;
import com.umeng.update.UmengUpdateListener;
import com.umeng.update.UpdateResponse;
import com.umeng.update.UpdateStatus;

public class MainActivity extends ModuleActivity implements OnClickListener,
	OnItemClickListener {

    ScrollViewPager mGuideViewPager;
    LinearLayout mGuideIndicatorLayout;
    @ViewInject(id = R.id.main_listview, itemClick = "onItemClick")
    ListView mMainListview;

    private TextView mClassDescriptionView;
    private LifeqImageView mClassImageView;

    private TextView mGalleryDescriptionView;
    private LifeqImageView mGalleryImageView;

    private TextView mOtherClassDescriptionView;
    private TextView mOtherClassIntroduceView;
    private LifeqImageView mOtherClassImageView;

    private View mClassTravelLayout;
    private View mGalleryLayout;

    private LayoutInflater inflate;
    private ArrayList<String> mCoverImageUrlList;
    CGetHomepage mCGetHomepage;

    List<HotRecommend> mHotRecommendList;

    private ScheduledExecutorService mScheduledExecutorService;
    private int mCurrentItem;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setNavigationTitle("仟途旅游");
	setMenuButtonVisibility(true);
	inflate = LayoutInflater.from(getApplicationContext());
	bindSlidingMenuClickEvent();
	initMainHeadView();
	getHomepageDetail();
	UmengUpdateAgent.update(this);
	BeeCloud.setAppIdAndSecret(BeeCloudUtil.APP_ID, BeeCloudUtil.APP_SECRET);
    }

    @Override
    protected void onResume() {
	super.onResume();
	mScheduledExecutorService = Executors
		.newSingleThreadScheduledExecutor();
	// 每隔2秒钟切换一张图片
	mScheduledExecutorService.scheduleWithFixedDelay(new ViewPagerTask(),
		3, 3, TimeUnit.SECONDS);
    }

    @Override
    protected void onStop() {
	super.onStop();
	if (!mScheduledExecutorService.isShutdown()) {
	    mScheduledExecutorService.shutdown();
	}
    }

    // 切换图片
    private class ViewPagerTask implements Runnable {

	@Override
	public void run() {
	    mCurrentItem = mGuideViewPager.getCurrentItem();
	    mCurrentItem++;

	    // 更新界面
	    handler.obtainMessage().sendToTarget();
	}
    }

    private WeakHandler<MainActivity> handler = new WeakHandler<MainActivity>(
	    MainActivity.this) {

	@Override
	protected void processMessage(MainActivity activity, Message msg) {
	    // 设置当前页面
	    mGuideViewPager.setCurrentItem(mCurrentItem, true);
	}
    };

    @Override
    public void onBackPressed() {
	onClickTwiceFinished();
    }

    private void bindSlidingMenuClickEvent() {
	mSlidingMenu.findViewById(R.id.head_image).setOnClickListener(
		new OnClickListener() {

		    @Override
		    public void onClick(View v) {
			Intent intent = new Intent(MainActivity.this,
				MyActivity.class);
			intent.putExtra(MyActivity.NAV_TITLE, "我的主页");
			intent.putExtra(MyActivity.IS_MY, true);
			startActivity(intent);
		    }
		});
	mSlidingMenu.findViewById(R.id.my_travel_layout).setOnClickListener(
		new OnClickListener() {

		    @Override
		    public void onClick(View v) {
			startActivity(new Intent(MainActivity.this,
				MyTravelActivity.class));
		    }
		});
	mSlidingMenu.findViewById(R.id.my_gallery_layout).setOnClickListener(
		new OnClickListener() {

		    @Override
		    public void onClick(View v) {
			startActivity(new Intent(MainActivity.this,
				MyGalleryListActivity.class));
		    }
		});
	mSlidingMenu.findViewById(R.id.proxy_statement_layout)
		.setOnClickListener(new OnClickListener() {

		    @Override
		    public void onClick(View v) {
			startActivity(new Intent(MainActivity.this,
				ProxyActivity.class));
		    }
		});
	mSlidingMenu.findViewById(R.id.check_update_layout).setOnClickListener(
		new OnClickListener() {

		    @Override
		    public void onClick(View v) {
			checkUpdateFromUmeng();
		    }
		});
	mSlidingMenu.findViewById(R.id.about_layout).setOnClickListener(
		new OnClickListener() {

		    @Override
		    public void onClick(View v) {
			startActivity(new Intent(MainActivity.this,
				AboutActivity.class));
		    }
		});
	mSlidingMenu.findViewById(R.id.contact_layout).setOnClickListener(
		new OnClickListener() {

		    @Override
		    public void onClick(View v) {
			startActivity(new Intent(MainActivity.this,
				ContactActivity.class));

		    }
		});
	mSlidingMenu.findViewById(R.id.logout).setOnClickListener(
		new OnClickListener() {

		    @Override
		    public void onClick(View v) {
			Logout logout = new Logout();
			final LoadingDialog loadingDialog = showLoadingDialog("退出当前账号...");
			MyRequest.request(MainActivity.this, logout,
				new ResponseCallback() {

				    @Override
				    public void process(boolean result,
					    Context context, Response data,
					    String msg) {
					canceledLoadingDialog(loadingDialog);
					if (result) {
					    GBLActivityManager
						    .getActivityManager()
						    .popAllActivityExceptOne(
							    null);
					    SysAppConfig.getInstance()
						    .clearClientConfig(context);
					    Intent intent = new Intent(context,
						    LoginActivity.class);
					    startActivity(intent);
					    toast("退出成功!");
					}
				    }
				});
		    }
		});
	LifeqImageView headPhotoView = ((LifeqImageView) mSlidingMenu
		.findViewById(R.id.head_image));
	User user = SysAppConfig.getInstance().getUser(getApplicationContext());
	if (user == null || StringUtils.isEmpty(user.getUser_name())) {
	    mSlidingMenu.findViewById(R.id.logout).setVisibility(View.GONE);
	    TextView userNameView = ((TextView) mSlidingMenu
		    .findViewById(R.id.user_name));
	    userNameView.setText("点击登录");
	    userNameView.setOnClickListener(new OnClickListener() {

		@Override
		public void onClick(View v) {
		    Intent intent = new Intent(MainActivity.this,
			    LoginActivity.class);
		    startActivity(intent);
		}
	    });
	    headPhotoView.setOnClickListener(new OnClickListener() {

		@Override
		public void onClick(View v) {
		    Intent intent = new Intent(MainActivity.this,
			    LoginActivity.class);
		    startActivity(intent);
		}
	    });
	    return;
	}

	headPhotoView.loadCircleImage(user.getHead_img_url(),
		ImageType.SourceImage);
	if (StringUtils.isEmpty(user.getAccount())) {
	    ((TextView) mSlidingMenu.findViewById(R.id.user_name))
		    .setText("尚未设置昵称");
	} else {
	    ((TextView) mSlidingMenu.findViewById(R.id.user_name)).setText(user
		    .getAccount());
	}
    }

    /**
     * 友盟检测更新
     */
    private void checkUpdateFromUmeng() {
	UmengUpdateAgent.setUpdateListener(new UmengUpdateListener() {
	    @Override
	    public void onUpdateReturned(int updateStatus,
		    UpdateResponse updateInfo) {
		switch (updateStatus) {
		case UpdateStatus.Yes: // has update
		    UmengUpdateAgent.showUpdateDialog(MainActivity.this,
			    updateInfo);
		    break;
		case UpdateStatus.No: // has no update
		    toast("已是最新版本");
		    break;
		case UpdateStatus.Timeout: // time out
		    toast("网络超时");
		    break;
		}
	    }
	});
	UmengUpdateAgent.forceUpdate(MainActivity.this);
    }

    private void setGuideViewPagerHeight() {
	int height = ScreenInfoUtil.getScreenWidth(MainActivity.this) / 2;
	RelativeLayout.LayoutParams layoutParams = (android.widget.RelativeLayout.LayoutParams) mGuideViewPager
		.getLayoutParams();
	layoutParams.height = height;
	mGuideViewPager.setLayoutParams(layoutParams);
    }

    private void initMainHeadView() {
	View headView = inflate.inflate(R.layout.main_head, null);

	mClassTravelLayout = headView.findViewById(R.id.class_travel_layout);
	mClassTravelLayout.setOnClickListener(this);
	mOtherClassImageView = (LifeqImageView) headView
		.findViewById(R.id.other_class_image);
	RelativeLayout.LayoutParams lp = (LayoutParams) mOtherClassImageView
		.getLayoutParams();
	lp.height = (ScreenInfoUtil.getScreenWidth(MainActivity.this) - ScreenInfoUtil
		.dp2px(MainActivity.this, 20)) * 9 / 16;
	mOtherClassImageView.setLayoutParams(lp);
	mOtherClassImageView.setOnClickListener(this);

	mGuideViewPager = (ScrollViewPager) headView
		.findViewById(R.id.guide_viewPager);
	setGuideViewPagerHeight();

	mClassDescriptionView = (TextView) headView
		.findViewById(R.id.class_description);
	mClassImageView = (LifeqImageView) headView
		.findViewById(R.id.class_image);

	mGalleryLayout = headView.findViewById(R.id.gallery_layout);
	mGalleryLayout.setOnClickListener(this);
	mGalleryDescriptionView = (TextView) headView
		.findViewById(R.id.gallery_description);
	mGalleryImageView = (LifeqImageView) headView
		.findViewById(R.id.gallery_image);

	mOtherClassIntroduceView = (TextView) headView
		.findViewById(R.id.other_class_introduce);
	mOtherClassDescriptionView = (TextView) headView
		.findViewById(R.id.other_class_description);
	mOtherClassImageView = (LifeqImageView) headView
		.findViewById(R.id.other_class_image);
	mGuideIndicatorLayout = (LinearLayout) headView
		.findViewById(R.id.guide_indicator_layout);

	mMainListview.addHeaderView(headView);

	mHotRecommendList = new ArrayList<HotRecommend>();
	CommonAdapter<HotRecommend> commonAdapter = new CommonAdapter<HotRecommend>(
		HotRecommendViewHolder.class, mHotRecommendList,
		MainActivity.this, R.layout.hot_recommend_item);
	mMainListview.setAdapter(commonAdapter);
    }

    /**
     * 获取首页详情
     */
    private void getHomepageDetail() {
	mCGetHomepage = new CGetHomepage();
	final LoadingDialog loadingDialog = showLoadingDialog("获取首页...");
	MyRequest.request(MainActivity.this, mCGetHomepage,
		new ResponseCallback() {

		    @Override
		    public void process(boolean result, Context context,
			    Response data, String msg) {
			canceledLoadingDialog(loadingDialog);
			if (result) {
			    HomePage homePage = data.getObject(HomePage.class);
			    /**
			     * 初始化轮播图
			     */
			    initCoverImageUrlList(homePage.getHomePictureList());
			    HomeClass homeClass = homePage.getHomeClass();
			    mClassDescriptionView.setText(homeClass
				    .getSchoolName());
			    mClassImageView.loadRoundImage(
				    homeClass.getSchoolPicurl(),
				    ImageType.SourceImage);

			    mGalleryDescriptionView.setText(homeClass
				    .getGalleryName());
			    mGalleryImageView.loadRoundImage(
				    homeClass.getGalleryPicurl(),
				    ImageType.SourceImage);

			    mOtherClassDescriptionView.setText(homeClass
				    .getOtherSchoolName()
				    + " "
				    + homeClass.getOtherSchoolClass()
				    + " "
				    + homeClass.getOtherSchoolRouteName());
			    mOtherClassIntroduceView.setText(homeClass
				    .getOtherSchoolRouteName());
			    mOtherClassImageView.loadRoundImage(
				    homeClass.getOtherSchoolPicurl(),
				    ImageType.SourceImage);
			    mHotRecommendList = data
				    .getList(HotRecommend.class);
			    CommonAdapter<HotRecommend> commonAdapter = new CommonAdapter<HotRecommend>(
				    HotRecommendViewHolder.class,
				    mHotRecommendList, context,
				    R.layout.hot_recommend_item);
			    mMainListview.setAdapter(commonAdapter);
			    setNetworkVisibility(false);
			}else {
			    setNetworkVisibility(true);
			}
			toast(msg);
		    }
		});
    }
    
    @Subscribe
    public void onRefresh(NetRefreshEvent netRefreshEvent) {
	setNetworkVisibility(false);
	getHomepageDetail();
    }
    

    @SuppressWarnings("deprecation")
    private void initCoverImageUrlList(ArrayList<Picture> homePictureList) {
	mCoverImageUrlList = new ArrayList<String>();
	for (Picture picture : homePictureList) {
	    mCoverImageUrlList.add(picture.getPicurl());
	}
	mGuideViewPager.setAdapter(pagerAdapter);
	mGuideViewPager.setCurrentItem(mCoverImageUrlList.size() * 100, false);
	pagerAdapter.notifyDataSetChanged();
	setUpGuideIndicatorLayout(mGuideIndicatorLayout);
	mGuideViewPager.setOnPageChangeListener(new OnPageChangeListener() {
	    
	    @Override
	    public void onPageSelected(int position) {
		int size = mGuideIndicatorLayout.getChildCount();
		for (int i = 0;i < size;i++) {
		  View indicator =  mGuideIndicatorLayout.getChildAt(i);
		  indicator.setSelected(false);
		}
		mGuideIndicatorLayout.getChildAt(position % mCoverImageUrlList.size()).setSelected(true);;
	    }
	    
	    @Override
	    public void onPageScrolled(int arg0, float arg1, int arg2) {
		
	    }
	    
	    @Override
	    public void onPageScrollStateChanged(int arg0) {
		
	    }
	});
    }

    PagerAdapter pagerAdapter = new PagerAdapter() {

	@Override
	public boolean isViewFromObject(View arg0, Object arg1) {
	    return arg0 == arg1;
	}

	public Object instantiateItem(ViewGroup container, int position) {
	    View convertView = inflate.inflate(R.layout.image_home_layout,
		    container, false);
	    ((LifeqImageView) convertView.findViewById(R.id.image))
		    .loadFile(
			    mCoverImageUrlList.get(position
				    % mCoverImageUrlList.size()),
			    ImageType.SourceImage, null, null);
	    container.addView(convertView);
	    return convertView;
	}

	public void destroyItem(ViewGroup container, int position, Object object) {
	    container.removeView((View) object);
	}

	@Override
	public int getCount() {
	    return Integer.MAX_VALUE;
	}
    };

    private void setUpGuideIndicatorLayout(LinearLayout guideIndicatorLayout) {
    	guideIndicatorLayout.removeAllViews();
	int indicatorSize = ScreenInfoUtil.dp2px(MainActivity.this, 10);
	for (int i = 0; i < mCoverImageUrlList.size(); i++) {
	    View indicator = inflate.inflate(R.layout.tab_guide, null);
	    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
		    indicatorSize, indicatorSize);
	    lp.setMargins(0, 0, indicatorSize, 0);
	    indicator.setLayoutParams(lp);
	    guideIndicatorLayout.addView(indicator);
	}
    }

    @Override
    public void onClick(View v) {
	int viewID = v.getId();
	switch (viewID) {
	case R.id.class_travel_layout:
	    startActivity(new Intent(MainActivity.this,
		    SchoolTravelListActivity.class));
	    break;
	case R.id.other_class_image:
	    startActivity(new Intent(MainActivity.this,
		    OtherClassTravelActivity.class));
	    break;
	case R.id.gallery_layout:
	    startActivity(new Intent(MainActivity.this,
		    MostBeautifulPhotoActivity.class));
	    break;
	}
    }

    @Override
    protected void initLayout(ViewGroup rootContentView) {
	addContentView(R.layout.activity_main);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
	    long id) {
	if (position > 0) {
	    HotRecommend hotRecommend = mHotRecommendList.get(position - 1);
	    Intent intent = new Intent(MainActivity.this,
		    SchoolTravelDetailActivity.class);
	    intent.putExtra(SchoolTravelDetailActivity.SCHOOL_TRAVEL_DETAIL_ID,
		    hotRecommend.getId());
	    intent.putExtra(SchoolTravelDetailActivity.HOT_RECOMMENT, true);
	    startActivity(intent);
	}
    }

}
